const fs = require('fs');
const path = require('path');

async function testM3U8Download() {
  const mediaID = 'kCtDawsZ'; // The media ID from your test
  const m3u8Url = `https://cdn.jwplayer.com/manifests/${mediaID}.m3u8`;
  const outputPath = path.join(__dirname, '..', 'test-output.m3u8');
  
  console.log('Testing m3u8 download approaches...');
  console.log('URL:', m3u8Url);
  
  // Approach 1: Try with Puppeteer using CDP
  try {
    console.log('\n=== Testing Approach 1: Puppeteer with CDP ===');
    const puppeteer = require('puppeteer');
    
    const browser = await puppeteer.launch({
      headless: 'new'
    });
    
    const page = await browser.newPage();
    
    // Enable network domain
    const client = await page.target().createCDPSession();
    await client.send('Network.enable');
    
    // Set headers
    await client.send('Network.setExtraHTTPHeaders', {
      headers: {
        'accept': '*/*',
        'accept-language': 'en-GB,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-US;q=0.6',
        'priority': 'u=1, i',
        'sec-ch-ua': '"Not;A=Brand";v="99", "Microsoft Edge";v="139", "Chromium";v="139"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'cross-site',
        'Referer': 'https://bigthink.com/'
      }
    });
    
    // Try to load the resource
    const response = await client.send('Network.loadNetworkResource', {
      frameId: page.mainFrame()._id,
      url: m3u8Url,
      options: {
        disableCache: false,
        includeCredentials: true
      }
    });
    
    console.log('CDP Response:', response);
    
    let m3u8Content;
    if (response.resource.success) {
      // Try to get response body
      try {
        const responseBody = await client.send('Network.getResponseBody', {
          requestId: response.resource.requestId
        });
        m3u8Content = responseBody.body;
        console.log('Successfully downloaded with CDP approach');
      } catch (err) {
        console.log('Failed to get response body:', err.message);
      }
    } else {
      console.log('Failed to load resource:', response.resource.errorMessage);
    }
    
    await browser.close();
    
    if (m3u8Content) {
      fs.writeFileSync(outputPath, m3u8Content);
      console.log('Saved m3u8 content to:', outputPath);
      return;
    }
  } catch (err) {
    console.log('Approach 1 failed:', err.message);
  }
  
  // Approach 2: Try with Puppeteer using fetch in page context
  try {
    console.log('\n=== Testing Approach 2: Puppeteer with fetch in page context ===');
    const puppeteer = require('puppeteer');
    
    const browser = await puppeteer.launch({
      headless: 'new'
    });
    
    const page = await browser.newPage();
    
    // Navigate to the main site first
    await page.goto('https://bigthink.com/', { 
      waitUntil: 'domcontentloaded',
      timeout: 30000 
    });
    
    // Try fetch in page context
    const result = await page.evaluate(async (url) => {
      try {
        const response = await fetch(url, {
          method: 'GET',
          headers: {
            'accept': '*/*',
            'Referer': 'https://bigthink.com/'
          }
        });
        
        if (response.ok) {
          const content = await response.text();
          return { success: true, content };
        } else {
          return { success: false, error: `HTTP ${response.status}` };
        }
      } catch (err) {
        return { success: false, error: err.message };
      }
    }, m3u8Url);
    
    console.log('Fetch result:', result);
    
    await browser.close();
    
    if (result.success) {
      fs.writeFileSync(outputPath, result.content);
      console.log('Saved m3u8 content to:', outputPath);
      return;
    }
  } catch (err) {
    console.log('Approach 2 failed:', err.message);
  }
  
  // Approach 3: Try with node-fetch but with different settings
  try {
    console.log('\n=== Testing Approach 3: Node-fetch with proxy-like settings ===');
    const fetch = require('node-fetch');
    
    const response = await fetch(m3u8Url, {
      method: 'GET',
      headers: {
        'accept': '*/*',
        'accept-language': 'en-GB,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-US;q=0.6',
        'Referer': 'https://bigthink.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0'
      }
    });
    
    if (response.ok) {
      const content = await response.text();
      fs.writeFileSync(outputPath, content);
      console.log('Saved m3u8 content to:', outputPath);
      return;
    } else {
      console.log('HTTP Error:', response.status, response.statusText);
    }
  } catch (err) {
    console.log('Approach 3 failed:', err.message);
  }
  
  console.log('\nAll approaches failed');
}

// Run the test
testM3U8Download().catch(console.error);